//
//  YHYEditHomePageViewController.m
//  Home
//
//  Created by 杨泓晔 on 16/4/23.
//  Copyright © 2016年 LanJue. All rights reserved.
//

#import "YHYEditHomePageViewController.h"
#import "YHYDesignerPTableViewCell.h"
#import "DCPaymentView.h"
//#import "YHYAddCVLastCellTableViewCell.h"
#import "WSRequirementView.h"
#import "TZTestCell.h"
#import "UIView+Layout.h"

#import "SeaPictureViewController.h"
#import "TZImagePickerController.h"
#import "YHYAddCVButtonTableViewCell.h"
@interface YHYEditHomePageViewController ()<UITableViewDelegate,UITableViewDataSource,WSRequirementViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate,YHYAddCVButtonDelegate>{
    NSInteger mun;
    NSInteger index;
    CGFloat _itemWH;
    CGFloat _margin;
    
    NSMutableArray *_selectedAssets;
    
    
    NSIndexPath *indexP;
    
    
}
@property (nonatomic,strong)NSArray *array;
@property (nonatomic,strong)UITableView *myTableView;
@property (nonatomic,strong)NSString *nameStr;
@property (nonatomic,strong)NSString *priceStr;
@property (nonatomic,strong)NSString *addressStr;
@property (nonatomic,strong)NSString *typeStr;//类型
@property (nonatomic,strong)NSString *styleStr;

@property (nonatomic,retain)TZTestCell *cell;

//@property (nonatomic,strong)AppDelegate *myAppDelegate;
@property (nonatomic,strong)UIView *myBackBigView;
@property (nonatomic,strong)NSMutableArray *mycollectionVArray;


@property (nonatomic,assign)NSInteger selectArray;



@property (nonatomic,strong)UICollectionViewFlowLayout *layout;
@property (nonatomic,strong)UICollectionView *myCollectionView;
@property (nonatomic,strong)UILabel *numLabel;
@property (nonatomic,strong)UIButton *button;


@property (nonatomic,retain)NSIndexPath *myindexPath;
@property (nonatomic,retain)NSMutableArray *seaArr;
@property (nonatomic,retain)UILabel *textnameL;
@property (nonatomic,retain)NSIndexPath *tapIndexPath;

@end

@implementation YHYEditHomePageViewController


- (void)viewWillAppear:(BOOL)animated {
    
    
    self.title = @"添加案例";
    self.tabBarController.tabBar.hidden=YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"arr" object:nil];
    self.tabBarController.tabBar.hidden=YES;
    self.navigationController.navigationBar.translucent = YES;
    
    
    [self.myCollectionView reloadData];
}

-(void) viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = LV;
    
    //    左侧的图标
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(Back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    _selectedAssets = [NSMutableArray array];
    self.myindexPath = [NSIndexPath new];
    _seaArr = [NSMutableArray array];
    self.numLabel = [UILabel new];
    self.tapIndexPath = [NSIndexPath new];
    _selectedPhotos = [NSMutableArray array];
    [self creatView];
}

- (void)creatView{
    self.array = [NSArray arrayWithObjects:@"作品名称", @"项目总价（元）", @"项目面积(㎡)", @"项目地址", @"项目类型", @"项目风格",nil];
    self.myTableView = [UITableView new];
    
    [self.view addSubview:self.myTableView];
    // self.myTableView.sectionFooterHeight = 10;
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(self.view);
        make.height.mas_equalTo(self.view.frame.size.height - 0 * AUTO_HEIGHT);
        make.width.mas_equalTo(self.view);
        
    }];
    
    // _myTableView.scrollEnabled = NO;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.backgroundColor = LV;
    [self.myTableView registerClass:[YHYDesignerPTableViewCell class] forCellReuseIdentifier:@"YHYDesignerPTableViewCell"];
    //图片
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    //button
    [self.myTableView registerClass:[YHYAddCVButtonTableViewCell class] forCellReuseIdentifier:@"YHYAddCVButtonTableViewCell"];
    [[UITableViewHeaderFooterView appearance] setTintColor:LV];
    self.myTableView.tableFooterView=[[UIView alloc]init];
    
    
    [_myTableView reloadData];
    
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        
        static NSString *str = @"YHYDesignerPTableViewCell";
        YHYDesignerPTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.xmLabel.text =[_array objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            cell.WXlabel.text = _nameStr;
        }
        if (indexPath.row == 1) {
            cell.WXlabel.text = _priceStr;
            
        }
        if (indexPath.row == 2) {
            cell.WXlabel.text = _addressStr;
        }
        
        if (indexPath.row == 4) {
            cell.WXlabel.text = _typeStr;
        }
        if (indexPath.row == 5) {
            cell.WXlabel.text = _styleStr;
        }
        
        return cell;
        
    }
    else if (indexPath.section == 1){
        static NSString *str = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = LV;
        
        indexP = indexPath;
        cell.backgroundColor = LV;
        self.layout = [[UICollectionViewFlowLayout alloc] init];
        _margin = 4 * AUTO_HEIGHT;
        _itemWH = (self.view.tz_width - 20 * AUTO_WIDTH-2 * _margin - 7) / 3 - _margin;
        self.layout.itemSize = CGSizeMake(_itemWH, _itemWH  - 1 );
        self.layout.minimumInteritemSpacing = _margin;
        self.layout.minimumLineSpacing = 10  * AUTO_HEIGHT ;
        _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0 * AUTO_WIDTH, SCREEN_WIDTH, _itemWH * 3 + _margin + 6 * AUTO_HEIGHT + 50 * AUTO_HEIGHT) collectionViewLayout:self.layout];
        self.myCollectionView.backgroundColor = [UIColor whiteColor];
        //    裁掉view的边界
        self.myCollectionView.layer.masksToBounds = NO;
        //    设置半径
        //self.myCollectionView.layer.cornerRadius = 6 * AUTO_WIDTH;
        self.myCollectionView.scrollEnabled = NO;
        // self.myCollectionView.backgroundColor = [UIColor whiteColor];
        
        [cell addSubview:_myCollectionView];
        
        
        
        
        
        _myCollectionView.contentInset = UIEdgeInsetsMake(15 * AUTO_WIDTH, 15 * AUTO_HEIGHT, 5 * AUTO_WIDTH, 15 * AUTO_HEIGHT);
        _myCollectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2 * AUTO_HEIGHT);
        _myCollectionView.dataSource = self;
        _myCollectionView.delegate = self;
        
        [_myCollectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
        
        
        UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
        [_myCollectionView addGestureRecognizer:longGesture];
        
        
        
        self.numLabel = [UILabel new];
        [cell addSubview:self.numLabel];
        self.numLabel.textColor = [UIColor blackColor];
        self.numLabel.alpha = 0.6;
        self.numLabel.font = [UIFont systemFontOfSize:TEXTLABELFONT*TEXTWEIGHT];
        [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_myCollectionView.mas_bottom).offset(11 * AUTO_HEIGHT);
            make.left.mas_equalTo(cell.mas_right).offset( - 50  * AUTO_WIDTH);
            make.height.mas_equalTo(15 * AUTO_WIDTH);
            
        }];
        NSLog(@"zzzzzzz%ld",(unsigned long)_selectedPhotos.count);
        self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
        //  [_myCollectionView reloadData];
        return cell;
        
    }
    if (indexPath.section == 2) {
        YHYAddCVButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHYAddCVButtonTableViewCell"];
        cell.delegate = self;
        return cell;
    }
    
    return nil;
}

- (void)buttonLongPressed:(UILongPressGestureRecognizer *)longPress
{
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
        {
            
            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
            CGPoint point = [longPress locationInView:_myCollectionView];
            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
            [_myCollectionView beginInteractiveMovementForItemAtIndexPath:selectedIndex];
            TZTestCell *mycell = (TZTestCell *)[_myCollectionView cellForItemAtIndexPath:selectedIndex];
            if (selectedIndex.row == _selectedPhotos.count) {
                //左后一个不抖动
            }
            else{
                [self shakeAnimationForView:mycell.imageView point:point];
            }
            
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [_myCollectionView updateInteractiveMovementTargetPosition:[longPress locationInView:_myCollectionView]];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            [_myCollectionView endInteractiveMovement];
            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
            CGPoint point = [longPress locationInView:_myCollectionView];
            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
            if (point.x < 50 || point.y < 50 || point.x > _itemWH * 3  - 30 || point.y > _itemWH * 3  - 40) {
                //          是图片
                
                [_selectedPhotos removeObjectAtIndex:_myindexPath.item];
                //   [_selectedPhotos removeObject:selectObject];
                NSLog(@"asasasas%@",_selectedPhotos);
                NSLog(@"zzzzzzz%ld",(unsigned long)_selectedPhotos.count);
                self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
                NSLog(@"sssssssss%ld",(long)_myindexPath.row);
                
                [_myCollectionView reloadData];
                // [_myTableView reloadData];
            }
        }
            break;
        default:
            [_myCollectionView cancelInteractiveMovement];
            break;
    }
    
    
}

- (void)shakeAnimationForView:(UIView *)view point:(CGPoint)point{
    //获取到当前的View
    CALayer *viewLayer = view.layer;
    //获取当前View位置
    CGPoint position = viewLayer.position;
    CGPoint x = CGPointMake(position.x + 9, position.y);
    CGPoint y = CGPointMake(position.x - 9, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    [animation setAutoreverses:YES];
    [animation setDuration:0.06];
    [animation setRepeatCount:3];
    [viewLayer addAnimation:animation forKey:nil];
    
    
}


//通知响应方法
- (void)change:(NSNotification *)notification
{
    NSMutableArray *ar = [notification object];
    self.selectedPhotos = ar;
    NSLog(@"qqqq%@",ar);
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    [_myCollectionView reloadData];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            DCPaymentView *payAlert = [[DCPaymentView alloc] init];
            payAlert.title = [NSString stringWithFormat:@"作品名称"];
            //[payAlert setTextFieldKeyBordToNum];
            //payAlert.numOfContent = 4;
            [payAlert show];
            payAlert.completeHandle = ^(NSString *inputPwd) {
                _nameStr = [NSString stringWithFormat:@"%@",inputPwd];
                
                [_myTableView reloadData];
                
            };
        }
        if (indexPath.row == 1) {
            DCPaymentView *price = [[DCPaymentView alloc]init];
            price.title = [NSString stringWithFormat:@"项目总价"];
            [price setTextFieldKeyBordToNum];
            price.numOfContent = 4;
            [price show];
            price.completeHandle = ^(NSString *inputPwd) {
                _priceStr = [NSString stringWithFormat:@"%@",inputPwd];
                
                [_myTableView reloadData];
                
            };
        }
        if (indexPath.row == 2) {
            DCPaymentView *address = [[DCPaymentView alloc]init];
            address.title = [NSString stringWithFormat:@"项目地址"];
            [address setTextFieldKeyBordToNum];
            address.numOfContent = 4;
            [address show];
            address.completeHandle = ^(NSString *inputPwd) {
                _addressStr = [NSString stringWithFormat:@"%@",inputPwd];
                
                [_myTableView reloadData];
                
            };
            
        }
        if (indexPath.row == 4) {
            mun = 1;
            NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1",@"3",@"4", nil];
            [self presentReire:array name:@"项目类型"];
            [_myTableView reloadData];
        }
        
    }
    if (indexPath.row == 5) {
        mun = 2;
        NSMutableArray *array = [NSMutableArray arrayWithObjects:@"11",@"33",@"44", nil];
        [self presentReire:array name:@"项目风格"];
        [_myTableView reloadData];
        
    }
    //    if (indexPath.section == 1) {
    //        NSLog(@"dwqd");
    //    }
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_selectedPhotos.count >= 9) {
        return _selectedPhotos.count;
    }
    else{
        return _selectedPhotos.count + 1;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    
    if (indexPath.row == _selectedPhotos.count) {
        
        self.cell.imageView.image = [UIImage imageNamed:@"jia"];
    } else {
        self.cell.imageView.image = _selectedPhotos[indexPath.row];
        //self.cell.highlighted = YES;
    }
    return self.cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"1111%ld",indexPath.row);
    if (indexPath.row == _selectedPhotos.count) {
        
        
        [self pickPhotoButtonClick:nil];
        
    }
    else{
        
        
        SeaPictureViewController *yhySeaVC = [SeaPictureViewController new];
        yhySeaVC.seaArray  = [NSMutableArray arrayWithArray:_selectedPhotos];
        yhySeaVC.indexNumber = (NSInteger)indexPath.item;
        
        [self.navigationController pushViewController:yhySeaVC animated:YES];
        
        
    }
    [_myCollectionView reloadData];
    
}
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    _myindexPath = indexPath;
    if ([collectionView numberOfItemsInSection:indexPath.section] <= 1) {
        return NO;
    }
    if (indexPath.row == _selectedPhotos.count) {
        return NO;
    }
    
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    
    
    _tapIndexPath = sourceIndexPath;
    if (destinationIndexPath.row != _selectedPhotos.count) {
        
        NSString *selectObject = _selectedPhotos[sourceIndexPath.item];
        self.myindexPath = sourceIndexPath;
        //从资源数组中移除该数据
        [_selectedPhotos removeObject:selectObject];
        
        
        
        NSMutableArray *destinationArr = _selectedPhotos;
        [destinationArr insertObject:selectObject atIndex:destinationIndexPath.row];
        
        
        
    }else{
        nil;
    }
    
    [collectionView reloadData];
    
    
}


#pragma mark Click Event

- (IBAction)pickPhotoButtonClick:(UIButton *)sender {
    //    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:self];
    NSInteger mum = 9;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:mum selectArr:_selectedPhotos delegate:self];
    imagePickerVc.selectCount = _selectedPhotos.count;
    NSLog(@"asas%ld",(long)imagePickerVc.selectCount);
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    [_selectedPhotos addObjectsFromArray:photos];
    
    //[self configCollectionView];
    
    _myCollectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    NSLog(@"%ld",_selectedPhotos.count);
    [_myCollectionView reloadData];
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return CGSizeMake(_itemWH, _itemWH);
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 2.0 * AUTO_WIDTH, 0);
}



- (void)presentReire:(NSMutableArray *)array name:(NSString *)title{
    WSRequirementView *view = [[WSRequirementView alloc]init];
    view.dataArr = array;
    view.delegate = self;
    view.titleLabel.text = title;
    
    [view showView];
}
- (void)getSelectData:(NSString *)dataStr{
    
    if (mun == 1) {
        _typeStr = dataStr;
    }
    if (mun == 2) {
        _styleStr = dataStr;
    }
    [_myTableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        // self.myTableView.rowHeight = 50 * AUTO_HEIGHT;
        return 50 * AUTO_HEIGHT;
    }
    if (indexPath.section == 1) {
        return 400 * AUTO_HEIGHT;
    }
    if (indexPath.section == 2) {
        return 100 * AUTO_HEIGHT;
    }
    
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return 8 * AUTO_HEIGHT;
    }
    
    //    if (section == 1) {
    //        return 15 * AUTO_HEIGHT;
    //    }
    return 0;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return _array.count;
    } else if (section == 1) {
        return 1;
    }
    if (section == 2) {
        return 1;
    }
    else{
        return 0;
    }
    
    
}

#pragma mark - button
- (void)presentDelegate:(NSInteger)tag{
    if (tag == 1001) {
        NSLog(@"保存");
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void) Back:(UIButton *) btn
{
    [self.navigationController popViewControllerAnimated:YES];

}

@end
